package com.example.allinonemanager.moudles.sys.service.impl;

import com.example.allinonemanager.base.exception.ServiceException;
import com.example.allinonemanager.base.response.StatusCode;
import com.example.allinonemanager.moudles.sys.dao.UserLoginDao;
import com.example.allinonemanager.moudles.sys.pojo.entity.UserEntity;
import com.example.allinonemanager.moudles.sys.pojo.req.UserLoginReq;
import com.example.allinonemanager.moudles.sys.pojo.req.UserRegisterReq;
import com.example.allinonemanager.moudles.sys.service.UserLoginService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.UUID;

@Slf4j
@Service
public class UserLoginServiceImpl implements UserLoginService {

    @Autowired
    private UserLoginDao userLoginDao;

    @Override
    public void register(UserRegisterReq userRegisterReq) {
        log.debug("注册业务: userRegisterReq={}", userRegisterReq);
        //用户名和密码不能为空
        if (StringUtils.isEmpty(userRegisterReq.getUserName()) || StringUtils.isEmpty(userRegisterReq.getPassword())) {
            log.debug("用户名或密码不能为空: userRegisterReq={}", userRegisterReq);
            throw new ServiceException(StatusCode.INPUT_NOT_NULL);
        }

        // 检查用户名是否已存在
        UserEntity existingUser = userLoginDao.selectByUserName(userRegisterReq.getUserName());
        if (!StringUtils.isEmpty(existingUser)) {
            throw new ServiceException(StatusCode.USERNAME_ALREADY_EXISTS);
        }

        UserEntity userEntity = new UserEntity();
        BeanUtils.copyProperties(userRegisterReq, userEntity);
        String uuid = UUID.randomUUID().toString();
        userEntity.setId(uuid);
        userEntity.setCreateTime(new Date());
        userLoginDao.insert(userEntity);
    }

    @Override
    public UserEntity login(UserLoginReq userLoginReq) {
        log.debug("登录业务: userLoginReq={}", userLoginReq);
        UserEntity userEntity = userLoginDao.selectByUserName(userLoginReq.getUserName());
        if(StringUtils.isEmpty(userEntity)){
            log.error("未找到用户: {}", userLoginReq.getUserName());
            throw new ServiceException(StatusCode.USERNAME_ERROR);
        }
        if(!userEntity.getPassword().equals(userLoginReq.getPassword())){
            log.error("密码不匹配: {}", userLoginReq.getPassword());
            throw new ServiceException(StatusCode.PASSWORD_ERROR);
        }
        return userEntity;
    }
}
